<!-- 联系人页 -->
<template>
  <div style="height: 100%;">
    <!-- 引入公共头部组件 -->
    <HeaderMenu
      title="联系人"
      leftText="返回"
      rightText="新建"
      @rightEvent="onClickRight"
    />

    <div style="width: 100%;">
      <!-- 吸顶布局 -->
      <van-sticky>
        <!-- 搜索区域 -->
        <van-search
          shape="round"
          background="#509DF7"
          show-action
          id="searchInput"
          placeholder="请输入联系人"
          @search="search"
          v-model="RegionParam[0].keyword"
          @clear="clear"
        >
          <div slot="action" @click="onSearch" style="color:#fff">搜索</div>
        </van-search>
      </van-sticky>

      <!--联系人列表数据 -->
      <div>
        <van-list
          style="padding-bottom: 50px;"
          v-model="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoading"
        >
          <div
            class="boxFormal"
            v-for="item in RegionList"
            :key="item.Id"
            @click="regionClick(item)"
          >
            <div class="companyName" style="font-size:14px">
              {{ item.CustomerName }}
            </div>
            <div class="code" style="font-size:14px">
              <div style="padding-right: 30px">姓名:{{ item.Name }}</div>
              <div>电话:{{ item.Tel_Code }}</div>
            </div>
            <div class="companyAddress" style="font-size:14px">
              {{ item.Address }}
            </div>

            <div
              style="padding-right: 15px; padding-left: 10px;display: flex;justify-content: flex-end;align-items: center;"
            >
              <van-button
                size="mini"
                @click.stop="recordChangeClick(0, item)"
                style="margin-top: 12px;"
                type="info"
                >编辑</van-button
              >
              <van-button
                size="mini"
                @click.stop="recordChangeClick(1, item)"
                style="margin-top: 12px;"
                type="danger"
                >删除</van-button
              >
            </div>
          </div>
        </van-list>
      </div>
    </div>

    <van-form
      @submit="onSubmit"
      v-if="active === '备案'"
      style="height: 100%;overflow: auto;box-sizing: border-box;display:none"
    >
      <div class="client">
        <van-field
          label="客户名称："
          :rules="[{ required: true, message: '请填写客户名' }]"
          v-model="entity.cCusName"
        >
        </van-field>
        <van-field
          label="省:"
          @click="showcProvince = true"
          v-model="entity.cProvinceName"
          readonly
        >
        </van-field>
        <van-popup v-model="showcProvince" position="bottom">
          <van-picker
            show-toolbar
            :columns="columnscProvince"
            @confirm="cProvinceConfirm"
            @cancel="showcProvince = false"
            value-key="name"
          />
        </van-popup>
        <van-field
          label="市:"
          @click="showcCity = true"
          v-model="entity.cCityName"
          readonly
        >
        </van-field>
        <van-popup v-model="showcCity" position="bottom">
          <van-picker
            show-toolbar
            :columns="columnscCity"
            @confirm="cCityConfirm"
            @cancel="showcCity = false"
            value-key="name"
          />
        </van-popup>
        <van-field
          label="区:"
          @click="showcCounty = true"
          v-model="entity.cCountyName"
          readonly
        >
        </van-field>
        <van-popup v-model="showcCounty" position="bottom">
          <van-picker
            show-toolbar
            :columns="columnscCounty"
            @confirm="cCountyConfirm"
            @cancel="showcCounty = false"
            value-key="name"
          />
        </van-popup>

        <van-field label="行业分类：" v-model="entity.cTrade"> </van-field>
        <van-field
          clickable
          readonly
          name="picker"
          @click="showPicker = true"
          v-model="entity.SaleType"
          label="销售性质"
          placeholder="销售性质"
        />
        <van-popup v-model="showPicker" position="bottom">
          <van-picker
            show-toolbar
            :columns="columns"
            @confirm="onConfirm"
            @cancel="showPicker = false"
          />
        </van-popup>

        <van-field
          readonly
          @click="CustomerChoice"
          right-icon="edit"
          label="上级单位: "
          placeholder="选择上级单位"
          v-model="entity.ParentName"
        >
          <!-- <Myuser @customerChoice="Client" ref="myuser" /> -->
        </van-field>

        <van-field
          clickable
          readonly
          name="picker"
          v-model="entity.cCusTypeName"
          label="客户类型"
          placeholder="点击选择客户类型"
        />
        <!-- @click="showType = true" -->

        <van-popup v-model="showType" position="bottom">
          <van-picker
            show-toolbar
            :columns="columnsType"
            @confirm="onTypeConfirm"
            @cancel="showType = false"
            value-key="name"
          />
        </van-popup>
        <!-- <van-field
              label="客户来源："
              v-model="entity.CustomerOrigin"
            ></van-field> -->
        <van-field label="营业执照：" v-model="entity.cCusPhone"></van-field>
        <van-field label="开票要求：" v-model="entity.IRInfo"></van-field>
        <van-field label="地址：" v-model="entity.cCusAddress"></van-field>
      </div>
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>

    <Myuser @customerChoice="Client" ref="myuser" v-if="ismyuser" />
  </div>
</template>

<script>
import { Card, Toast, Dialog } from "vant";

import { Search, NavBar, Pagination, Divider, Icon, Sticky } from "vant";
// import Viewdetails from "./Viewdetails.vue";
import Myuser from "../../components/OwnUser.vue";
import PaginationCom from "../../components/PaginationCom.vue";
// 引入公共头部组件
import HeaderMenu from "../../components/VolHeaderMenu.vue";
export default {
  components: {
    Myuser,
    PaginationCom,
    // Viewdetails,
    "van-icon": Icon,
    "van-divider": Divider,
    "van-pagination": Pagination,
    "van-nav-bar": NavBar,
    "van-card": Card,
    "van-search": Search,
    "van-sticky": Sticky,
    // 公共头部组件
    HeaderMenu
    // Edit
  },
  data() {
    return {
      // 是否新建联系人
      isAddRecord: false,
      ismyuser: false,
      showcProvince: false,
      showType: false,
      showcCounty: false,
      listChildren: [],
      showcCity: false,
      columnscProvince: [], //省
      columnscCity: [], //市
      columnscCounty: [], //区
      // 备案
      showType: false,
      columnsType: [
        {
          name: "备案",
          Id: -1
        },
        {
          name: "潜在",
          Id: 0
        },
        {
          name: "正式",
          Id: 1
        },
        {
          name: "休眠",
          Id: 2
        }
      ],
      activeNames: ["1"],
      value: "",
      showArea: false,
      areaList: {},
      columns: [],
      showPicker: false,
      entity: {
        cCusTypeName: "备案客户"
      },
      info: {},
      RegionList: [], //联系人
      active: "备案",
      loading: false,
      finished: false,
      Regifinished: false,
      Regiloading: false,
      pagination: {
        current: 1,
        pageSize: 5,
        // 总条数
        Total: 0,
        showTotal: 0
        //   `总数:${total} 当前:${range[0]}-${range[1]}`,
        // pageSizeOptions: ["15", "30", "60"], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        // showSizeChanger: true
      },
      Total: 0,
      Keyword: "",
      data: [],
      dataList: [],
      PageRows: 25,
      queryParam: [
        { condition: "cCusName" },
        { condition: "cCusType", keyword: null }
      ],
      RegionParam: [{ condition: "Name" }],
      height: 0
    };
  },
  async created() {
    // 清空数据
    this.RegionList = [];
    // 获取联系人数据
    this.getRegionList();
    //  去除加载状态
    this.loading = false;
    // await this.Op();
    // this.getDataList();
    // this.getRegionList();
    // this.getSelsct();
    // this.getlist();
  },
  mounted() {
    this.onSearch()
    //挂载成功后给pop事件绑定一个方法
    // 如果支持 popstate （一般移动端都支持）
    // if (window.history && window.history.pushState) {
    //   // 往历史记录里面添加一条新的当前页面的url
    //   history.pushState(null, null, document.URL);
    //   // 给 popstate 绑定一个方法用来监听页面返回
    //   window.addEventListener("popstate", this.back, false); //false阻止默认事件
    // }
  },

  //组件销毁后清除事件
  destroyed() {},

  methods: {
    // 输入框搜索按钮
    onSearch() {
      this.search();
    },
    back() {
      this.$router.go(0);
      console.log(this.ismyuser);
      console.log("监听到了");
    },
    activechange(a) {
      console.log("切换");
    },
    //获取省份信息
    getlist() {
      this.http
        .post("/Base_BasicData/Base_District/GetDataListByPId?pId=0", {})
        .then(resJson => {
          this.ListProvince = resJson.Data;
          this.columnscProvince = resJson.Data.map(item => {
            return item.Name;
          });
          if (!this.flag) {
            console.log(123);
            // this.getDataList();
          }
        });
    },
    //市级change
    city(e) {
      this.http
        .post("/Base_BasicData/Base_District/GetDataListByPId?pId=" + e, {})
        .then(resJson => {
          this.listChildren = resJson.Data;
          this.columnscCity = resJson.Data.map(item => {
            return item.Name;
          });
          //市
          if (this.entity.cCity) {
            let arr2 = [this.entity.cCity].reduce((pre, cur) => {
              let idx = this.listChildren.findIndex(im => im.Id == cur);
              console.log(idx);
              pre.push(this.listChildren[idx]);
              return pre;
            }, []);
            if (arr2) {
              this.entity.cCityName = arr2[0].Name;
              this.entity.cCity = arr2[0].Id;
            }
          }
        });
    },

    //区
    village(e) {
      this.http
        .post("/Base_BasicData/Base_District/GetDataListByPId?pId=" + e, {})
        .then(resJson => {
          this.listcounty = resJson.Data;
          this.columnscCounty = resJson.Data.map(item => {
            return item.Name;
          });

          if (this.entity.cCity) {
            let arr3 = [this.entity.cCounty].reduce((pre, cur) => {
              let idx = this.listcounty.findIndex(im => im.Id == cur);

              pre.push(this.listcounty[idx]);
              return pre;
            }, []);
            if (arr3) {
              this.entity.cCountyName = arr3[0].Name;
              this.entity.cCounty = arr3[0].Id;
            }
          }
        });
    },

    //区
    cCountyConfirm(value) {
      this.entity.cCountyName = value;

      let arr = [this.entity.cCountyName].reduce((pre, cur) => {
        let idx = this.listcounty.findIndex(im => im.Name == cur);
        console.log(idx);
        pre.push(this.listcounty[idx]);
        return pre;
      }, []);
      console.log(arr);
      this.entity.cCountyName = arr[0].Name;
      this.entity.cCounty = arr[0].Id;

      this.showcCounty = false;
    },
    //市
    cCityConfirm(value) {
      this.entity.cCityName = value;

      let arr = [this.entity.cCityName].reduce((pre, cur) => {
        let idx = this.listChildren.findIndex(im => im.Name == cur);
        console.log(idx);
        pre.push(this.listChildren[idx]);
        return pre;
      }, []);
      console.log(arr);
      this.entity.cCityName = arr[0].Name;
      this.entity.cCity = arr[0].Id;
      this.village(this.entity.cCity);
      this.showcCity = false;
    },
    //省
    cProvinceConfirm(value) {
      console.log(value);
      this.entity.cProvinceName = value;

      let arr = [this.entity.cProvinceName].reduce((pre, cur) => {
        let idx = this.ListProvince.findIndex(im => im.Name == cur);
        console.log(idx);
        pre.push(this.ListProvince[idx]);
        return pre;
      }, []);
      console.log(arr);
      this.entity.cProvinceName = arr[0].Name;
      this.entity.cProvince = arr[0].Id;
      this.city(this.entity.cProvince);
      this.showcProvince = false;
    },
    Viewdetails(Id, cCusCode) {
      this.$router.push({
        path: "/formal/Viewdetails",
        query: {
          Id,
          cCusCode
        }
      });
      // this.$refs.viewdetails.openForm(Id, cCusCode);
      // viewdetails
    },
    // 联系人列表点击
    regionClick(item) {
      this.$router.push({
        path: "/record/Edit",
        query: { Id: item.Id, readonly: 2, urlType: 0 }
      });
    },
    // 联系人列表加载
    onLoading() {
      this.loading = true; //防止第一页重复加载
      // 获取联系人列表数据
      this.getRegionList();
    },
    // 联系人列表编辑和删除
    recordChangeClick(type, item) {
      if (type == 0) {
        // 点击的是编辑
        this.$router.push({
          path: "/record/Edit",
          query: { Id: item.Id, readonly: 1, urlType: 0 }
        });
      } else {
        // 点击的是删除
        // 删除（
        Dialog.confirm({
          message: "确定要删除吗",
          confirmButtonColor: "#1989fa"
        })
          .then(() => {
            this.http
              .post("/CustomerManagement/Cust_CustomerLinkMan/DeleteData", [
                item.Id
              ])
              .then(resJson => {
                if (resJson.Success) {
                  this.$toast("删除成功");
                  // 页数初始化
                  this.pagination.current = 1;
                  // 列表数据清空
                  this.RegionList = [];
                  // 获取联系人列表数据
                  this.getRegionList();
                } else {
                  this.$toast("删除失败");
                  this.loading = false;
                }
              });
          })
          .catch(() => {
            console.log(123);
          });
      }
    },

    btn(row) {
      this.$refs.edit.openForm(row);
    },
    // 搜索框清除按钮
    clear() {
      this.RegionParam = [{ condition: "cCusName" }];
      // 列表数据清空
      this.RegionList = [];
      // 是否显示页面加载
      this.loading = true;
      // 重置数据没有全部加载完成。继续加载
      this.finished = false;
      // 获取联系人列表数据
      this.getRegionList();
    },
    Regionclear() {
      this.RegionParam = [{ condition: "cCusName" }];
      this.getRegionList();
    },
    // 返回到上一页
    onClickLeft() {
      this.$router.back();
    },
    // 新建联系人
    onClickRight() {
      this.Regifinished = false;
      this.loading = false;
      this.$router.push({
        path: "/record/Add"
      });
    },
    //弹出页面
    Edit(item) {},

    //搜索
    search(value) {
      // 页数重置
      this.pagination.current = 1;
      // 列表数据清空
      this.RegionList = [];
      // 是否显示页面加载
      this.loading = true;
      // 重置化没有加载完成。重新加载
      this.finished = false;
      if (this.RegionParam.keyword !== "") {
        // 开始加载联系人列表
        this.onLoading();
      }
    },
    Regionsearch(value) {
      console.log(value);

      // this.RegionParam[0].keyword = value;
      this.getRegionList();
    },

    //获取联系人列表数据
    getRegionList() {
      this.selectedRowKeys = [];
      this.http
        .post(
          "/CustomerManagement/Cust_CustomerLinkMan/GetDataListOfMySelfCustomerInfoByConditions",
          {
            // 当前页数
            PageIndex: this.pagination.current,
            // 每页显示10条
            PageRows: 10,
            SortField: "Id",
            SortType: "desc",
            Search: this.RegionParam
          }
        )
        .then(resJson => {
          if (resJson.Success) {
            let rows = resJson.Data;
            // 赋值总条数
            this.pagination.Total = resJson.Data.Total;
            if (resJson.Data.length == 0 || resJson.Data == null) {
              // 停止加载
              this.loading = false;
              // 数据全部加载完成
              this.finished = true;
              return;
            }
            if (rows.length < this.pageSize) {
              // 最后一页不足10条的情况
              this.finished = true;
            }
            // 处理数据
            if (this.pagination.current === 1) {
              // 如果是第一页。正常赋值
              this.RegionList = rows;
            } else {
              // 如果不是第一页数据 正常拼接
              this.RegionList = this.RegionList.concat(rows);
            }
            //  停止加载
            this.loading = false;
            // 数据全部加载完成
            this.finished = true;

            return;
          } else {
            Toast.fail(resJson.Msg);
            // 停止加载
            this.loading = false;
            // 结束加载
            this.finished = true;
          }

          // 注意，，必须return  否则接口回频繁请求
          return;
        });
    },

    // 备案
    //本条客户的数据
    Client(a) {
      console.log(a);
      this.$set(this.entity, "ParentName", a.cCusName);
      this.$set(this.entity, "ParentId", a.Id);
    },
    //选择客户
    CustomerChoice() {
      this.ismyuser = true;
      this.$nextTick(() => {
        this.$refs.myuser.openForm();
      });
    },
    //客户类型
    onTypeConfirm(value) {
      this.entity.cCusTypeName = value.name;
      this.entity.cCusType = value.Id;
      this.showType = false;
    },
    AddRecord(obj) {
      this.http
        .post("/CustomerManagement/Cust_CustomerApply/SaveData", obj)
        .then(res => {
          if (res.Success) {
            // this.$message.success('操作成功')
          } else {
            this.$message.error(res.Msg);
          }
        });
    },
    async Op() {
      await this.http.post("/Base_Manage/Home/GetOperatorInfo").then(res => {
        if (res.Success) {
          this.info = res.Data.UserInfo;
          console.log(this.info);
          // this.$message.success('操作成功')
        } else {
          this.$message.error(res.Msg);
        }
      });
    },

    onSubmit(values) {
      this.entity.cCusTypeName = -1;
      this.http
        .post("/CustomerManagement/CustomerInfo/SaveData", this.entity)
        .then(resJson => {
          console.log("获取提交的最后结果", resJson);
          this.loading = false;
          if (resJson.Success) {
            Toast.success("操作成功");
            this.active = 0;
            this.entity = {
              cCusTypeName: "备案客户"
            };
            console.log(this.info);
            let obj = {};
            obj.CustomerId = resJson.Data.Id;
            obj.CustomerName = resJson.Data.cCusName;
            obj.Id = null;
            obj.SalesmanId = this.info.Id;
            obj.SalesmanName = this.info.RealName;
            obj.ApprovalStatus = resJson.Data.cCusType;
            obj.ApplyDate = resJson.Data.CreateTime;
            obj.Type = "3";
            console.log(obj);
            this.AddRecord(obj);
            // 返回主页面/首页    可以回到上一页
            window.history.go(-1);
          } else {
            Toast(resJson.Msg);
          }
        });
    },
    onConfirm(value) {
      this.entity.SaleType = value;
      this.showPicker = false;
    },

    getSelsct() {
      this.http
        .post("/Base_BasicData/Base_DictionaryMain/GetTheDataByDicKey", {
          Condition: "DicKey",
          Keyword: "SaleType"
        })
        .then(res => {
          this.columns = res.Data.DictionaryDetailsList;
          console.log(this.columns);

          if (this.columns && this.columns.length > 0) {
            this.columns = this.columns.map(item => {
              return item.DicName;
            });
          }
          console.log(this.columns);
        });
    }
  },
   // 监听路由
   watch: {
    $route(a,b) {
      this.onSearch();
    }
  }
};
</script>

<style lang="less" scoped>
/* 覆盖van-button的默认样式 */
.van-button {
  padding: 0 10px 0 10px !important;
}
.search-none {
  // margin-top: -120px !important;
  // 为了解决进到页面后如果是显示检索状态条件下  下拉还会出现数据和检索提示拼接的问题
  height: 0 !important;
}
.fixedbox {
  position: fixed;
  bottom: 0;
  right: 0;
  /* height: 50px; */
  background: #fff;
  width: 100vw;
}
.pagination {
  position: absolute;
  bottom: 5px;
  right: 20%;
}
.code {
  display: flex;
  justify-content: start;
  margin-left: 10px;
  color: #777;
}
.Foricon {
  color: blue;
  position: absolute;
  right: 8px;
}
.btn {
  position: absolute;
  bottom: 0;
  right: 0;
}

.formalBox {
  // height: calc(100vh - 150px);
  padding-bottom: 50px;
  box-sizing: border-box;
  overflow: auto;
}

.companyName {
  padding-top: 10px;
  margin-left: 10px;
  margin-bottom: 5px;
  color: #000000;
  font-weight: 600;
  font-size: 18px;
  line-height: 1.8;
}
.companyAddress {
  padding-top: 10px;
  margin-left: 10px;

  color: #777;
  // font-weight: 600;
  // font-size: 18px;
  line-height: 1.3;
}
.boxFormal {
  box-shadow: 2px 2px 5px #ccc;
  border-radius: 5px;
  // position: relative;

  width: 95%;
  /* height: 80px; */
  padding-bottom: 10px;
  margin: 3px auto;
  margin-bottom: 10px;
}
</style>
